import Vue from 'vue'
import VueRouter from 'vue-router'

const Login = () => import("../views/Login");
const Home = () => import("../views/Home");
const Welcome = () => import('@/views/Welcome')
const Users = () => import('@/components/user/Users')
const Rights = () => import('@/components/power/Rights')
const Roles = () => import('@/components/power/Roles')
const Category = () => import('@/components/goods/Category')
const Params = () => import('@/components/goods/Params')
const GoodsList = () => import('@/components/goods/List')
const AddGoods = () => import('@/components/goods/AddGoods')
const Order = () => import('@/components/order/Order')
const Report = () => import('@/components/report/Report')

// 解决导航冗余
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/home', redirect: '/welcome', component: Home, children: [
      { path: '/welcome', component: Welcome },
      { path: '/users', component: Users },
      { path: '/rights', component: Rights },
      { path: '/roles', component: Roles },
      { path: '/categories', component: Category },
      { path: '/params', component: Params },
      { path: '/goods', component: GoodsList },
      { path: '/goods/add', component: AddGoods },
      { path: '/orders', component: Order },
      { path: '/reports', component: Report },
    ]
  },

]

const router = new VueRouter({
  routes
})

// 导航守卫 判断token值
router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  // from 代表从哪个路径跳转而来
  // next 是一个函数，表示放行 next()放行 next('/login')强制跳转
  if (to.path === '/login') return next()
  // 获取token
  const loginToken = sessionStorage.getItem('token')
  // 如果没有token则需要登录
  if (!loginToken) return next('/login')
  // 放行
  next()
})

export default router
